#!/usr/bin/python
import sys
import XenAPI
import urllib2
import base64
from xml.dom.minidom import parse, parseString

path 	  =  "./"
resultxml = path +"result.xml"
certfile  = path +"tpm.cert"
pubkey    = path +"xen.pub"
aikblob   = path +"aik_tcpa.pub"
aikpub   = path  +"aik_pem.pub"

def read_xml(result):
    dom = parseString(result)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    blob  = dom.getElementsByTagName("xentxt:aiktcpa")[0]
    aikpubkey  = dom.getElementsByTagName("xentxt:aikpub")[0]
    print xencert.firstChild.nodeValue
    print xenpub.firstChild.nodeValue

    f= open (certfile,"w")
    cert = base64.b64decode(xencert.firstChild.nodeValue)
    f.write(cert)

    f.close()
    f = open(pubkey,"w")
    key = base64.b64decode( xenpub.firstChild.nodeValue)
    f.write(key)
    f.close()

    f = open(aikblob,"w")
    f.write(base64.b64decode(blob.firstChild.nodeValue))
    f.close()

    f = open(aikpub,"w")
    f.write( base64.b64decode(aikpubkey.firstChild.nodeValue))
    f.close()



def main(session):
    host_ref = session.xenapi.session.get_this_host(session.handle)
    args = {}
    ret_val = session.xenapi.host.call_plugin(host_ref, 'tpmGetAttestationKey', 'main', args)
    f = open(resultxml,"w")
    f.write(ret_val);
    read_xml(ret_val)
    print ret_val

if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password> "
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    session = XenAPI.Session(url)
    session.xenapi.login_with_password(username, password)
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

